package com.water_work_form.controller;

import com.water_work_form.result.Result;
import com.water_work_form.result.ResultCodeEnum;
import com.water_work_form.result.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Api(tags = {"图片 前端控制器"})
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 图片文件夹地址
     */
    @Value("${file.path}")
    private String filePath;

    /**
     * 图片上传至指定文件夹
     * @param file 选择的文件
     * @return 返回新的图片名（当前时间+随机数）
     * @throws IOException 读写异常
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResultUtil.error(ResultCodeEnum.ERROR,"上传文件为空");
        }
        String fileName = file.getOriginalFilename();
        String extend = "."+ FilenameUtils.getExtension(fileName);
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+extend;
        File fileDir = new File(filePath + newFileName);
        if(!fileDir.getParentFile().exists()){
            fileDir.getParentFile().mkdirs();
        }
        file.transferTo(fileDir);
        return ResultUtil.success(ResultCodeEnum.SUCCESS,newFileName);
    }

}
